<template>
  <div class="fileBox">
    <div class="nav_left">
      <span class="tree_top" ref="treeTop"></span>
      <el-tree
        ref="tree"
        :data="treeData"
        node-key="id"
        :default-expanded-keys="expandedKeys"
        @node-click="nodeClick"
        style="padding: 10px 0">
            <span class="custom-tree-node" slot-scope="{ node, data }">
            <el-tooltip class="item" effect="dark" :offset="100" :content="node.label" placement="left"
                        v-if="node.label.length >= 8">
               <span class="treeContent">{{ node.label }}</span>
              </el-tooltip>
               <span class="treeContent" v-if="node.label.length < 8">{{ node.label }}</span>
            <span class="treeEdit">
               <el-button type="text" size="mini" @click="() => append(data)">
                <i class="el-icon-circle-plus" :style="node.level === 1 ? 'font-size:16px':'font-size:16px;display:none'"></i>
              </el-button>
              <el-button type="text" size="mini" @click="() => editEvent(data)">
                <i class="el-icon-edit" :style="node.level === 1 ? 'font-size:16px;display:none':'font-size:16px'"></i>
              </el-button>
            </span>
          </span>
      </el-tree>
      <el-dialog
        title=""
        :visible.sync="dialogVisible"
        width="35%"
        :modal-append-to-body='false'
        :before-close="handleClose">
        <div style="height: 40px;">
          <span style="float: left;width: 30%;line-height: 40px;text-align: center;font-size: 18px" v-if="applyType === 1">{{titleName}} :</span>
          <span style="float: left;width: 18%;line-height: 40px;text-align: center;font-size: 18px" v-if="applyType === 2">{{titleName}} :</span>
          <el-input style="float:left;width: 60%;line-height: 40px" v-model="name" v-if="applyType === 1"></el-input>
          <el-input style="float:left;width: 70%;line-height: 40px" v-model="name" v-if="applyType === 2"></el-input>
        </div>
        <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="SureEvent">确 定</el-button>
         </span>
      </el-dialog>

    </div>
    <div class="content_right">
      <div style="margin: 20px 0 10px 0">
        <el-input placeholder="请输入内容" v-model="fuzzySearch" style="width: 20%;margin-right: 20px" clearable
                  @input="fuzzyInput(fuzzySearch)">
          <el-button slot="append" icon="el-icon-search" @click="searchvalEvent"></el-button>
        </el-input>
        <el-select v-model="status" placeholder="请选择是否有效" @change="sfyxEvent(status)" clearable>
          <el-option
            v-for="item in statusSearch"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button style="float: right;margin-left: 20px;" type="primary" @click="addUserEvent(3,1)"> + 添加用户</el-button>
        <el-button style="float: right;" type="primary" @click="addPermissions"> + 批量添加用户权限</el-button>
      </div>
      <el-table :border="true" :data="tableData" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号"  prop="index" sortable width="80"></el-table-column>
        <el-table-column label="姓名" prop="displayname" align='center' width="120px"></el-table-column>
        <el-table-column label="账号" prop="account" align='center'></el-table-column>
        <el-table-column label="身份证号" prop="sid" align='center'></el-table-column>
        <el-table-column label="手机号" prop="phone" align='center'></el-table-column>
        <el-table-column label="邮箱" prop="email" align='center'></el-table-column>
        <el-table-column label="状态" prop="status" align='center'>
          <template slot-scope="scope">
            <template v-if="scope.row.status === 1 || scope.row.status === 2">
              有效
            </template>
            <template v-if="scope.row.status === 0">
              无效
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" align='center' width="260">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="seeUserEvent(6,1,scope.row)">查看</el-button>
            <el-button size="mini" type="primary" @click="editUserEvent(scope.row)">编辑</el-button>
            <el-button size="mini" type="primary" @click="configurationAdmin(7,1,scope.row)">配置权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;margin: 20px 0;height: 40px;line-height: 40px">
        <div style="float: right">
          <el-pagination v-if="paginationShow" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                         :current-page="currentPage4" :page-sizes="[10, 20, 30, 40, 50]" :page-size="10"
                         layout="total, sizes, prev, pager, next, jumper" :total=total></el-pagination>
        </div>
      </div>

      <el-dialog title="提示" :visible.sync="AdoptVisbile" width="30%" center :modal-append-to-body="false">
        <span>确定批量添加用户权限吗？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="AdoptVisbile = false">取 消</el-button>
          <el-button type="primary" @click="Adopt">确 定</el-button>
        </span>
      </el-dialog>

      <!--  弹框 -->
      <el-dialog title="编辑用户" :visible.sync="seeUser" width="35%"
                 :before-close="handleUserClose" :modal-append-to-body="false">
        <el-form :model="editUserForm" :rules="rules" ref="editUserForm" label-width="130px">
          <el-form-item label="身份证号" prop="sid" class="el_w">
            <el-input v-model="editUserForm.sid">
            </el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="displayname" class="el_w">
            <el-input v-model="editUserForm.displayname"></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="account" class="el_w">
            <el-input v-model="editUserForm.account"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex" class="el_w">
            <el-select v-model="editUserForm.sex" placeholder="请输入性别" style="width: 100%">
              <el-option
                v-for="item in sexBox"
                :key="item.id"
                :label="item.value"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述" prop="description" class="el_w">
            <el-input v-model="editUserForm.description"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" class="el_w">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone" class="el_w">
            <el-input v-model="editUserForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status" class="el_w">
            <el-select v-model="editUserForm.status" placeholder="请选择状态" style="width: 100%">
              <el-option
                v-for="item in statusBox"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择科室" prop="department" class="el_w">
            <el-select v-model="editUserForm.department" placeholder="请输入性别" style="width: 100%">
              <el-option
                v-for="item in idBox"
                :key="item.id"
                :label="item.department"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAddUser">确 定</el-button>
        </span>
      </el-dialog>

    </div>
  </div>
</template>

<script>
  import {http} from "../../../assets/commonjs/axios";
  import {$aos} from "../../../store/state";
  import {delSurplus} from "../../../assets/commonjs/utils";

  export default {
    name: "userManage",
    data() {
      return {
        AdoptVisbile: false,
        multipleSelection: [],
        // ================== 操作科室 ==========================
        paginationShow:true,
        kzbl: null,
        treeData: [{
          id: null,
          label: "上海城乡建设管委会项目审核",
          parentId: 1,
          children: []
        },
        ],
        expandedKeys: [4],
        dialogVisible: false,
        titleName: "",
        id: null,
        name: null,
        expandedid: '',
        // =============================================
        statusValue:'',
        status:'',
        fuzzySearch: '',
        orgId: '',
        applyType: '',
        tableData: [],
        pages: '',//每页条数
        pgindex: '',//当前页
        loading: true,
        currentPage4: 1,
        total: 0,
        statusSearch: [///状态的下拉框数据
          {value: 1, label: "无效"},
          {value: 2, label: "有效"},
        ],
        // ================ 编辑用户 ======================
        seeUser: false,
        editUserForm: {
          department:'',//科室id
          urId:'',
          uid: '',
          applyType: 2,//1：新建 2.编辑 3.删除 4 预览
          sid: '',//身份证号
          displayname: '',//姓名
          account: '',//账号
          sex: "",//性别
          description: "",//描述
          email: "",//邮箱,
          phone: "",//手机号
          status: "",//状态
        },
        rules: {
          sid: [
            {required: true, message: "请填写身份证号", trigger: "blur"}
          ],
          displayname: [
            {required: true, message: "请填写姓名", trigger: "blur"}
          ],
          account: [
            {required: true, message: "请填写账号", trigger: "blur"}
          ],
          sex: [
            {required: true, message: "请选择性别", trigger: "blur"}
          ],
          email: [
            {required: true, message: "请填写邮箱", trigger: "blur"}
          ],
          phone: [
            {required: true, message: "请填写手机号", trigger: "blur"}
          ],
          department: [
            {required: true, message: "请选择科室Id", trigger: "change"}
          ],

        },
        sexBox: [   //性别的下拉框数据
          {id: "男", value: "男"},
          {id: "女", value: "女"},
        ],
        idBox:[],
        statusBox: [///状态的下拉框数据
          {value: 0, label: "无效"},
          {value: 1, label: "有效"},
        ],
        // ===============================================
      }
    },
    created() {
      $aos.getItem('loginData').then(res => {
        this.treeData[0].label = res.org.orgname;
        this.orgId = res.org.orgid;
        this.seeksEvent();
      })
    },
    methods: {
      Adopt() {
        this.AdoptVisbile = false;
        let urIds = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          urIds.push(parseFloat(this.multipleSelection[i].urIds));
        }
        $aos.setItem('urIdList', urIds.toString());
        $aos.setItem('tabNum', 7);
        this.$router.push({path: '/containerDetail', query: {index: 1}})
      },
      addPermissions() {
        if (this.multipleSelection === undefined || this.multipleSelection.length === 0) {
          this.$message({type: 'warning', message: '请选择用户后操作！'});
        } else {
          this.AdoptVisbile = true;
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = [];
        val.forEach(item => {
          this.multipleSelection.push({
            urIds: item.urId
          })
        })
      },
      append(data) {
        if (data.parentId === 1) {
          this.applyType = 1;
          this.titleName = "内设处（科）室名称"
          this.id = null;
          this.name = '';
          this.dialogVisible = true;
        } else {
          this.$message({message: '此项不可以编辑', type: 'warning'});

        }

      },
      editEvent(data) {
        if (data.parentId === null) {
          this.applyType = 2;
          this.titleName = "重命名";
          this.id = data.id;
          this.name = data.label;
          this.dialogVisible = true;
        } else {
          this.$message({message: '此项不可以编辑', type: 'warning'});
        }
      },
      nodeClick(data) {

        //===============用于强制改变页面的数字为1=========;
        this.paginationShow = false;
        this.handleCurrentChange(1,"zh");
        this.$nextTick(function () {
          this.paginationShow = true;
        })
        //===============================================;

        this.expandedid = data.id;
        this.id = data.id;
        this.editUserForm.department = data.id
        // if (data.id != 2) {
          this.$refs.treeTop.style.zIndex = "-1"
        // }
        //保存科室id:
        $aos.setItem('ksId', data.id);
        $aos.setItem('ksName',data.label);
        this.pageIndex = 1;
        this.searchUserList({
          orgId: this.orgId,
          depId: data.id,
          status: '',
          fuzzySearch: '',
          pageIndex: this.pgindex,
          pageNum: this.pages,
        })
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      //保存或编辑时弹出层的确定事件
      SureEvent() {
        this.getKs();
        this.dialogVisible = false;
      },
      //获取科室数据事件
      seeksEvent() {
        this.applyType = 4;
        this.seeKs();
      },
      //模糊查询
      searchvalEvent() {
        this.searchUserList({fuzzySearch: this.searchValue,status: this.status});
      },
      fuzzyInput(val) {
        if (val === '') {
          this.searchValue = ''
          this.searchUserList({orgId: this.orgId,status: this.status});
        }
      },
      //查询筛选是否有效
      sfyxEvent(){
        this.searchUserList({fuzzySearch: this.searchValue,status: this.status});
      },
      //获取相应的单位
      unitEvent(val) {
      },
      //添加用户事件
      addUserEvent(key, index) {
        if(this.id){
          $aos.setItem('tabNum', key)
          this.$router.push({path: '/containerDetail', query: {index: index, orgId: this.orgid}})
        }else{
          this.$message({message: '请选择科室', type: 'warning'});
        }
      },

      //科室的编辑和添加
      getKs() {
        http('post', 'permission/operate_department', {
          applyType: this.applyType,
          id: this.id,
          orgId: this.orgId,
          name: this.name
        }).then(res => {
          if (res.data.success) {
            this.$message({message: res.data.msg, type: 'success'});
            this.applyType = 4;
            this.seeKs()
          } else {
            this.$message({message: res.data.msg, type: 'warning'});
          }
        })
      },
      //科室的查看
      seeKs() {
        http('post', 'permission/operate_department', {
          applyType: this.applyType,
          id: null,
          orgId: this.orgId,
          name: null
        }).then(res => {
          if (res.data.success) {
            let datas = res.data.data;
            if (datas.length) {
              this.idBox = datas;
              this.treeData[0].children = this.getJsonTree(datas, null);
              this.expandedKeys = [this.treeData[0].children[0].id];
              this.id =this.expandedKeys[0]
            } else {
              this.$refs.treeTop.style.zIndex = "-1"
            }
            this.searchUserList({
              orgId: this.orgId,
              depId:this.id || '',
            });
          }
        })

      },

      //递归方法 生成 json tree 数据
      getJsonTree(data, parentId) {
        let itemArr = [];
        for (let i = 0; i < data.length; i++) {
          let node = data[i];
          if (node.parentId === parentId) {
            let newNode = {};
            newNode.id = node.id;
            newNode.parentId = node.parentId;
            newNode.label = node.department;
            itemArr.push(newNode);
          }

        }
        return itemArr;
      },
      //查询用户列表
      searchUserList(val) {
        http('post', 'permission/list_user', {
          orgId: val.orgId || this.orgId,
          status: val.status || this.status || 0,
          depId: val.depId || this.id || null,
          fuzzySearch: val.fuzzySearch || this.fuzzySearch || null,
          pageIndex: val.pageIndex || this.pageIndex || 1,
          pageNum: val.pageNum || this.pageNum || 10
        }).then(res => {
          if (res.data.success) {
            let data = res.data.data;
            let info = data.list || [];
            if (info) {
              //保留this
              var _this = this
              info.forEach(function (item, index) {
                //分页
                if (_this.pages == 0) {
                  if (val.pageIndex > 1) {
                    item.index = (val.pageIndex - 1) * 10 + index + 1;
                  } else {
                    item.index = index + 1
                  }
                } else if (_this.pages != 0) {
                  if (val.pageIndex > 1) {
                    item.index = (val.pageIndex - 1) * _this.pages + index + 1;
                  } else {
                    item.index = index + 1
                  }
                }
              })
              this.tableData = info
              this.loading = false;
              this.total = data.total;
            }
          }
        })
      },


      //改变每页条数事件
      handleSizeChange(val) {
        this.pages = val
        this.searchUserList({
          orgId: '',
          status: '',
          depId: this.id || '',
          fuzzySearch: '',
          pageIndex: this.pgindex,
          pageNum: this.pages,
        })
      },
      //改变当前是第几页
      handleCurrentChange(val,str) {
        this.pgindex = val
        if(!str){
          this.searchUserList({
            orgId: '',
            status: '',
            depId: this.id || '',
            fuzzySearch: '',
            pageIndex: this.pgindex,
            pageNum: this.pages,
          })
        }
      },


      seeUserEvent(key, index, row) {
        $aos.setItem('tabNum', key)
        $aos.setItem('userData', row)
        this.$router.push({path: '/containerDetail', query: {index: index, orgId: row.orgid}})
      },
      //编辑用户关闭事件
      handleUserClose(done) {
        this.$refs.editUserForm.resetFields();
        done()
      },

      //管理员编辑弹窗确定事件
      submitAddUser() {
        http('post', 'permission/opera_user', {
          user: this.editUserForm
        }).then(res => {
          if (res.data.success) {
            this.$message({message: res.data.msg, type: 'success'});
            this.seeUser = false;
            this.searchUserList({
              orgId: this.orgId,
              depId:this.editUserForm.department
            });
          } else {
            this.$message({message: res.data.msg, type: 'warning'});
          }
        })
      },

      editUserEvent(row) {
        this.seeUser = true;
        this.editUserForm = delSurplus(row, this.editUserForm);
        this.editUserForm.applyType = 2;
        this.editUserForm.department = this.id
      },
      configurationAdmin(key, index, row) {
        $aos.setItem('tabNum', key);
        $aos.setItem('userData', row)
        $aos.setItem('urIdList', row.urId.toString())
        this.$router.push({path: '/containerDetail', query: {index: index}})
      },
    }
  }
</script>

<style scoped>
  .fileBox {
    height: 95%;
    width: 100%;
  }

  .tree_top {
    width: 100%;
    height: 26px;
    background: rgba(154, 176, 212, 0.4);
    color: red;
    position: absolute;
    top: 36px;
    z-index: 100;
  }

  .nav_left {
    height: 100%;
    background: white;
    width: 300px;
    float: left;
    position: relative;
  }

  .treeContent {
    display: inline-block;
    width: 170px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .nav_left >>> .el-tree-node:focus > .el-tree-node__content, .el-tree-node__content:hover {
    background: rgba(154, 176, 212, 0.4);
  }

  .nav_left >>> div.el-tree-node__content:hover span.treeEdit {
    display: inline-block;
  }

  .treeEdit {
    display: none;
    padding-left: 30px;
  }

  .content_right {
    /*height: calc(100% - 40px);*/
    height: 100%;
    float: right;
    width: calc(100% - 320px);
    overflow: auto;
    position: relative;
  }
</style>
